# 封装数据库工具类
import pymysql

class DButil(object):
    conn = None

    @classmethod
    def __get_conn(cls):
        if  cls.conn is None:
            cls.conn = pymysql.connect(host="localhost", port=3306,  user="root",password="123",
                                   database="test_db",charset="utf8")
        return cls.conn

    @classmethod
    def __close_conn(cls):
        if cls.conn is not None:
            cls.conn.close()
            cls.conn = None

    @classmethod
    def select_one(cls, sql):
        cursor = None
        res = None
        try:
            # 建议连接
            cls.conn = cls.__get_conn()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql语句
            cursor.execute(sql)
            # 查询一条语句
            res = cursor.fetchone()
        except Exception as err:
            print("sql语句异常：", str(err))
        finally:
            # 关闭游标
            cursor.close()
            # 关闭 连接
            cls.__close_conn()
            return res

    @classmethod
    def updateId_db(cls,sql):
        cursor = None
        try:
            # 建议连接
            cls.conn = cls.__get_conn()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql语句
            cursor.execute(sql)
            # 影响的行数
            print("影响的行数：", cls.conn.affected_rows())
            # 提交 事务
            cls.conn.commit()
        except Exception as err:
            cls.conn.rollback()
            print("sql语句出现异常：",str(err))

        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__close_conn()


if __name__ == '__main__':
    res = DButil.select_one("select * from t_book;")
    print(res)

    # DButil.updateId_db("update t_book set is_delete = 1 where id = 7;")
    # DButil.updateId_db(f"delete from bs_user where mobile='{13831224243}'")